package com.hp.bon.sgw.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessCaller {
	private Process process = null;

	public void stopProccess() {
		if (process != null) {
			process.destroy();
		}

	}

	public void startProgram(String[] programCmd) throws IOException {
		ProcessBuilder builder = new ProcessBuilder(programCmd);
		builder.redirectErrorStream(true);
		process = builder.start();
		ProgressStreamOutter streamOutter = new ProgressStreamOutter(process);
		streamOutter.start();

	}

	public static void main(String[] args) throws Exception {
		String COMMAND[] = { "javaw.exe", "-cp", ".;bin;lib/*",
				"com.hp.bon.sgw.start.SGWCoreStarter" };
		new ProcessCaller().startProgram(COMMAND);
		Thread.currentThread().join();
	}

	static class ProgressStreamOutter extends Thread {
		private Process process;

		public ProgressStreamOutter(Process process) {
			this.setName("ProgressStreamOutter");
			this.setDaemon(true);
			this.process = process;
		}

		public void run() {
			try {
				// PrintWriter pw = new PrintWriter(System.out);
				BufferedInputStream in = new BufferedInputStream(
						process.getInputStream());
				BufferedReader br = new BufferedReader(
						new InputStreamReader(in));
				String line = null;
				while ((line = br.readLine()) != null) {
					System.out.println(line);
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

	}
}
